package com.iaroc.ios;

import java.net.DatagramSocket;
import java.net.DatagramPacket;

/*
 * iOSAccelerometerReceiver: Class that sets up a Datagram connection to an
 * iOS device and parses the data for useful accelerometer x, y and z values.
 * 
 * @author gerberduffy
 */
public class iOSAccelerometerReceiver {

	public static final int PORT = 10552;
	private DatagramSocket s;	//Our socket	
  private int port;          //Port to listen for a connection on
	
   
  /* Accelerometer Values:
   * X: Pivot around the axis that runs from the speaker to the home button.
   * Y: Pivot around the horizontal axis.
   * Z: Refers to face-up and face-down (not very useful to us). Face-up --> positive value, Face-down --> negative value.
   */
  private double x, y, z;
	
   
  
	public iOSAccelerometerReceiver(int port){
		this.port = port;
	}
	
   
  /*
	 * Listen on a port for incoming client connections
	 * form iOS devices.
	 * @param port The port to listen on
	 */
   public void connect(){
		try {
                s = new DatagramSocket(port);   //Connect on the specified port
                }
                catch(Exception e){System.out.println("Connection Established"); System.exit(1);}
                while(s.isBound()){
                        try { //Thread.sleep(1000);
                            byte[] buf = new byte[256];
                            DatagramPacket p = new DatagramPacket(buf, buf.length);
                            s.receive(p);
    
                            String[] outputs = new String(p.getData()).split(",");
             
                            x = Double.parseDouble(outputs[2]);
                            y = Double.parseDouble(outputs[3]);
                            z = Double.parseDouble(outputs[4]);

                        
                        } catch(Exception e){
                                System.out.println("Something failed");
                        }
                }
	}

}

